import React, { useState, useRef, useEffect } from 'react'
import { 
  Input, 
  Button, 
  Avatar, 
  Tag,
  Empty,
  Spin,
  Select,
  message,
  Tooltip 
} from 'antd'
import {
  SendOutlined,
  UserOutlined,
  RobotOutlined,
  ClearOutlined,
  DeleteOutlined,
  ThunderboltOutlined,
  CopyOutlined,
  PlusOutlined
} from '@ant-design/icons'
import ReactMarkdown from 'react-markdown'
import aiService from '@/services/ai'
import './index.less'

const { TextArea } = Input
const { Option } = Select

interface Message {
  id: string
  role: 'user' | 'assistant'
  content: string
  timestamp: Date
  model?: string
}

const AIChat: React.FC = () => {
  const [messages, setMessages] = useState<Message[]>([])
  const [inputValue, setInputValue] = useState('')
  const [loading, setLoading] = useState(false)
  const [currentModel, setCurrentModel] = useState('deepseek-r1:14b')
  const [temperature, setTemperature] = useState(0.7)
  const [sessionId, setSessionId] = useState<string>(crypto.randomUUID())
  const messagesEndRef = useRef<HTMLDivElement>(null)
  const abortControllerRef = useRef<AbortController | null>(null)

  // 自动滚动到底部
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
  }

  useEffect(() => {
    scrollToBottom()
  }, [messages])

  // 发送消息
  const handleSend = async () => {
    if (!inputValue.trim()) {
      message.warning('请输入消息')
      return
    }

    const userMessage: Message = {
      id: Date.now().toString(),
      role: 'user',
      content: inputValue,
      timestamp: new Date()
    }

    setMessages(prev => [...prev, userMessage])
    setInputValue('')
    setLoading(true)

    // 创建 AbortController 用于取消请求
    abortControllerRef.current = new AbortController()

    // 创建一个临时的助手消息
    const assistantMessageId = (Date.now() + 1).toString()
    const assistantMessage: Message = {
      id: assistantMessageId,
      role: 'assistant',
      content: '',
      timestamp: new Date(),
      model: currentModel
    }

    setMessages(prev => [...prev, assistantMessage])

    try {
      // 使用 AI 服务获取流式响应（带 sessionId）
      const reader = await aiService.streamChat(
        {
          message: inputValue,
          model: currentModel,
          temperature: temperature,
          sessionId: sessionId  // 传递会话ID
        },
        abortControllerRef.current.signal
      )

      // 累积内容
      let accumulatedContent = ''

      // 解析 SSE 流
      await aiService.parseSSEStream(
        reader,
        // onMessage: 收到消息时
        (response) => {
          if (!response.IsComplete) {
            const newContent = response.Message || ''
            accumulatedContent += newContent

            // 更新助手消息
            setMessages(prev => prev.map(msg =>
              msg.id === assistantMessageId
                ? { ...msg, content: accumulatedContent }
                : msg
            ))
          }
        },
        // onComplete: 完成时
        () => {
          setLoading(false)
        },
        // onError: 错误时
        () => {
          message.error('流处理失败')
        }
      )

    } catch (error: any) {
      if (error.name === 'AbortError') {
        message.info('请求已取消')
      } else {
        message.error('发送消息失败，请稍后重试')

        // 移除失败的助手消息
        setMessages(prev => prev.filter(msg => msg.id !== assistantMessageId))
      }
    } finally {
      setLoading(false)
      abortControllerRef.current = null
    }
  }

  // 停止生成
  const handleStop = () => {
    if (abortControllerRef.current) {
      abortControllerRef.current.abort()
      setLoading(false)
      message.info('已停止生成')
    }
  }

  // 清空对话
  const handleClear = () => {
    setMessages([])
    message.success('已清空对话')
  }

  // 新建对话（创建新的 sessionId）
  const handleNewSession = () => {
    setMessages([])
    setSessionId(crypto.randomUUID())
    message.success('已创建新对话')
  }

  // 删除单条消息
  const handleDeleteMessage = (id: string) => {
    setMessages(prev => prev.filter(msg => msg.id !== id))
  }

  // 复制消息内容
  const handleCopyMessage = async (content: string) => {
    try {
      await navigator.clipboard.writeText(content)
      message.success('已复制到剪贴板')
    } catch (error) {
      message.error('复制失败')
    }
  }

  // 按回车发送
  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault()
      if (!loading) {
        handleSend()
      }
    }
  }

  // 渲染 AI 内容，处理 <think> 标签（支持实时流式输出）
  const renderAIContent = (content: string) => {
    if (!content) {
      return <div>思考中...</div>
    }

    const parts: JSX.Element[] = []
    let key = 0

    // 检查是否包含 <think> 标签
    if (content.includes('<think>')) {
      // 分割内容：处理完整的和未完成的 think 块
      const thinkStartRegex = /<think>/g
      const thinkEndRegex = /<\/think>/g
      
      let currentIndex = 0

      // 找到所有 <think> 和 </think> 的位置
      const thinkStarts: number[] = []
      const thinkEnds: number[] = []
      
      let match
      while ((match = thinkStartRegex.exec(content)) !== null) {
        thinkStarts.push(match.index)
      }
      while ((match = thinkEndRegex.exec(content)) !== null) {
        thinkEnds.push(match.index)
      }

      // 处理内容
      for (let i = 0; i < thinkStarts.length; i++) {
        const startPos = thinkStarts[i]
        const endPos = thinkEnds[i]

        // 添加 think 之前的内容
        if (startPos > currentIndex) {
          const beforeThink = content.substring(currentIndex, startPos)
          if (beforeThink.trim()) {
            parts.push(
              <ReactMarkdown key={`content-${key++}`}>{beforeThink}</ReactMarkdown>
            )
          }
        }

        // 处理 think 块
        if (endPos !== undefined) {
          // 完整的 think 块
          const thinkContent = content.substring(startPos + 7, endPos)
          if (thinkContent.trim()) {
            parts.push(
              <details key={`think-${key++}`} className="think-block" open>
                <summary>💭 思考过程</summary>
                <div className="think-content">
                  <ReactMarkdown>{thinkContent}</ReactMarkdown>
                </div>
              </details>
            )
          }
          currentIndex = endPos + 8 // </think> 的长度
        } else {
          // 未完成的 think 块（实时显示）
          const thinkContent = content.substring(startPos + 7)
          parts.push(
            <details key={`think-${key++}`} className="think-block think-streaming" open>
              <summary>💭 思考过程 <span className="streaming-dot">...</span></summary>
              <div className="think-content">
                <ReactMarkdown>{thinkContent || '正在思考...'}</ReactMarkdown>
              </div>
            </details>
          )
          currentIndex = content.length
          break
        }
      }

      // 添加剩余内容
      if (currentIndex < content.length) {
        const remaining = content.substring(currentIndex)
        if (remaining.trim()) {
          parts.push(
            <ReactMarkdown key={`content-${key++}`}>{remaining}</ReactMarkdown>
          )
        }
      }

      return parts.length > 0 ? <>{parts}</> : <ReactMarkdown>{content}</ReactMarkdown>
    }

    // 没有 think 标签，直接渲染
    return <ReactMarkdown>{content}</ReactMarkdown>
  }

  return (
    <div className="ai-chat-page">
      <div className="chat-wrapper">
        {/* 头部区域 */}
        <div className="chat-header">
          <div className="header-left">
            <RobotOutlined className="title-icon" />
            <span className="title-text">AI 智能助手</span>
            <Tag
              color="purple"
              icon={<ThunderboltOutlined />}
              style={{
                background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                border: 'none',
                color: 'white',
                borderRadius: '12px',
                padding: '4px 12px',
                fontWeight: 600,
                fontSize: '12px'
              }}
            >
              DeepSeek R1
            </Tag>
          </div>
          <div className="header-right">
            <Tooltip title="选择模型">
              <Select
                value={currentModel}
                onChange={setCurrentModel}
                style={{ width: 180 }}
                size="middle"
              >
                <Option value="deepseek-r1:14b">🚀 DeepSeek R1 14B</Option>
                <Option value="deepseek-r1:7b">⚡ DeepSeek R1 7B</Option>
                <Option value="deepseek-r1:1.5b">⚡ DeepSeek R1 1.5B</Option>
              </Select>
            </Tooltip>
            <Tooltip title="调整创造性">
              <Select
                value={temperature}
                onChange={setTemperature}
                style={{ width: 130 }}
                size="middle"
              >
                <Option value={0.3}>🎯 精确</Option>
                <Option value={0.7}>⚖️ 平衡</Option>
                <Option value={1.0}>🎨 创意</Option>
              </Select>
            </Tooltip>
            <Tooltip title="新建对话">
              <Button
                icon={<PlusOutlined />}
                onClick={handleNewSession}
                size="middle"
                type="primary"
              >
                新建
              </Button>
            </Tooltip>
            <Tooltip title="清空当前对话">
              <Button
                icon={<ClearOutlined />}
                onClick={handleClear}
                size="middle"
                disabled={messages.length === 0}
              >
                清空
              </Button>
            </Tooltip>
          </div>
        </div>

        {/* 消息区域 */}
        <div className="messages-area">
          <div className="messages-scroll">
            {messages.length === 0 ? (
              <div className="empty-state">
                <Empty
                  image={Empty.PRESENTED_IMAGE_SIMPLE}
                  description={
                    <>
                      <div className="empty-title">✨ 你好！我是 DeepSeek R1 智能助手</div>
                      <div className="empty-desc">我可以帮你解答问题、编写代码、分析数据等。快来和我聊天吧！</div>
                    </>
                  }
                />
              </div>
            ) : (
              <>
                {messages.map((msg) => (
                  <div key={msg.id} className={`message-item ${msg.role}`}>
                    <div className="message-avatar">
                      <Avatar
                        icon={msg.role === 'user' ? <UserOutlined /> : <RobotOutlined />}
                        style={{
                          backgroundColor: msg.role === 'user' ? '#1890ff' : '#52c41a'
                        }}
                      />
                    </div>
                    <div className="message-content">
                      <div className="message-header">
                        <span className="message-role">
                          {msg.role === 'user' ? '你' : 'AI 助手'}
                        </span>
                        {msg.model && (
                          <Tag color="blue" style={{ fontSize: '11px', padding: '0 6px' }}>
                            {msg.model}
                          </Tag>
                        )}
                        <span className="message-time">
                          {msg.timestamp.toLocaleTimeString()}
                        </span>
                        <Button
                          type="text"
                          size="small"
                          icon={<CopyOutlined />}
                          onClick={() => handleCopyMessage(msg.content)}
                          className="copy-btn"
                          title="复制"
                        />
                        <Button
                          type="text"
                          size="small"
                          icon={<DeleteOutlined />}
                          onClick={() => handleDeleteMessage(msg.id)}
                          className="delete-btn"
                          title="删除"
                        />
                      </div>
                      <div className="message-bubble">
                        {msg.role === 'assistant' ? (
                          renderAIContent(msg.content || '思考中...')
                        ) : (
                          msg.content
                        )}
                      </div>
                    </div>
                  </div>
                ))}
                {loading && (
                  <div className="loading-state">
                    <Spin tip="🤔 AI 正在深度思考中..." size="large" />
                  </div>
                )}
                <div ref={messagesEndRef} />
              </>
            )}
          </div>
        </div>

        {/* 输入区域 */}
        <div className="input-area">
          <div className="input-wrapper">
            <TextArea
              value={inputValue}
              onChange={(e) => setInputValue(e.target.value)}
              onKeyDown={handleKeyDown}
              placeholder="✨ 输入你的问题... (Shift+Enter 换行，Enter 发送)"
              autoSize={{ minRows: 3, maxRows: 8 }}
              disabled={loading}
            />
          </div>
          <div className="input-actions">
            {loading ? (
              <Button
                type="primary"
                danger
                icon={<ClearOutlined />}
                onClick={handleStop}
              >
                停止生成
              </Button>
            ) : (
              <Button
                type="primary"
                icon={<SendOutlined />}
                onClick={handleSend}
                disabled={!inputValue.trim()}
              >
                发送
              </Button>
            )}
          </div>
        </div>
      </div>
    </div>
  )
}

export default AIChat

